#
# Log functions for the FileTable
#
package FileTable::Log;

use strict;

use DBI;
use Carp;
use English;
use HTTP::Date;

use FileTable;

use vars qw($sqlcreate $defauthority);

$sqlcreate = <<EoF;
create table f_log (
   uniqueid integer AUTO_INCREMENT PRIMARY KEY,
   tablename varchar(16),
   reckey varchar(64),
   operation varchar(8),
   data text,
   date datetime,
   authority varchar(64),
   INDEX (tablename, reckey, date),
   INDEX (tablename, date)
)
EoF

# Set default authority on init.
if ($ENV{REMOTE_USER}) {
    $defauthority = "web:$ENV{REMOTE_USER}";
} elsif ($ENV{REQUEST_METHOD}) {
    $defauthority = "web:any-user";
} else {
    $defauthority = "unix:" . $EUID;
}

sub inittable {
    my $dbhandle = $FileTable::dbhandle;
    $dbhandle->do($sqlcreate) || croak "Create statement failed";
}

sub writelog {
    my ($table, $key, $data, $date, $authority, $operation) = @_;

    FileTable::dbconnect() if !$FileTable::dbhandle;
    my $dbhandle = $FileTable::dbhandle;
    

    my $writestm = $dbhandle->prepare("INSERT DELAYED INTO f_log
         (tablename, reckey, operation, data, date, authority)
         VALUES (?, ?, ?, ?, ?, ?)");
    $writestm->{PrintError} = 0;
    my $status = $writestm->execute(
	      $table, $key, $operation, $data, $date, $authority);

    if (!$status) {
	if ($writestm->errstr =~ /Unknown table/ | $writestm->errstr =~ /doesn't exist/) {
            inittable();
            $writestm->{PrintError} = 1;
            $status = $writestm->execute(
	        $table, $key, $operation, $data, $date, $authority);
        } else {
            croak "Log error: " . $writestm->errstr;
        }
    }
}
	
sub log {
    my ($table, $key, $data, $operation) = @_;

    my $date = HTTP::Date::time2iso(time());
    if (!$operation) {
	if (!defined($data) || $data == '') {
	    $operation = "delete";
	} else {
	    $operation = "update";
	}
    }
    writelog($table, $key, $data, $date, $defauthority, $operation);
}

sub history {
    my ($table, $key) = @_;
    my @results;
    my $elm;

    FileTable::dbconnect() if !$FileTable::dbhandle;
    my $dbhandle = $FileTable::dbhandle;
    
    my $stm = $dbhandle->prepare("select * from f_log
                     where tablename = ? and reckey = ?");
    my $count = $stm->execute($table, $key);
    while ($elm = $stm->fetchrow_hashref()) {
	push(@results, $elm);
    }
    return @results;
}
